/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelMoverPalete.java
 *
 * Created on 23/09/2011, 22:30:25
 */

package modules.enderecamento.gui.jpanel;

import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import modules.enderecamento.exception.EspacoExcedidoRuaException;
import modules.enderecamento.facade.WMSFacade;
import modules.enderecamento.gui.custom.LimitedIntegerJTextField;
import modules.enderecamento.gui.custom.WMSJTextField;
import modules.enderecamento.models.dto.Palete;
import modules.enderecamento.models.dto.Rua;
import modules.enderecamento.models.dto.custom.OcupacaoPalete;
import modules.enderecamento.util.BoxPanel;
import modules.enderecamento.util.Funcoes;
import modules.enderecamento.validation.Validation;

/**
 *
 * @author Clezio
 */
public class PanelMoverPalete extends javax.swing.JPanel {

    private WMSFacade wmsFacade;
    /** Creates new form PanelMoverPalete */
    public PanelMoverPalete() {
        initComponents();
        wmsFacade = new WMSFacade();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.enderecamento.gui.custom.WMSJTable();
        btnTransferir = new modules.enderecamento.gui.custom.WMSJButton();
        tfConfirmar = new modules.enderecamento.gui.custom.WMSJTextField();
        lbConfirmar = new modules.enderecamento.gui.custom.WMSLabel();
        wMSLabel6 = new modules.enderecamento.gui.custom.WMSLabel();
        lbRuaDestino = new modules.enderecamento.gui.custom.WMSLabel();
        tfRuaDestino = new modules.enderecamento.gui.custom.WMSJTextField();
        lbRuaOrigem = new modules.enderecamento.gui.custom.WMSLabel();
        tfRuaOrigem = new modules.enderecamento.gui.custom.WMSJTextField();
        tfPalete = new LimitedIntegerJTextField(10);
        lbPalete = new modules.enderecamento.gui.custom.WMSLabel();
        jLabel1 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Palete", "Ocupado (m³)", "Disponível (m³)"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnTransferir.setMnemonic('T');
        btnTransferir.setText("Transferir");
        btnTransferir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTransferirActionPerformed(evt);
            }
        });
        btnTransferir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnTransferirKeyPressed(evt);
            }
        });

        tfConfirmar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyReleased(evt);
            }
        });

        lbConfirmar.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbConfirmar.setText("Confimar dados:");

        wMSLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        wMSLabel6.setText("(S) ou (N)");

        lbRuaDestino.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbRuaDestino.setText("Rua (Destino):");

        tfRuaDestino.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfRuaDestinoFocusLost(evt);
            }
        });
        tfRuaDestino.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfRuaDestinoKeyPressed(evt);
            }
        });

        lbRuaOrigem.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbRuaOrigem.setText("Rua (Origem):");

        tfRuaOrigem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfRuaOrigemFocusLost(evt);
            }
        });
        tfRuaOrigem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfRuaOrigemKeyPressed(evt);
            }
        });

        tfPalete.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfPaleteFocusLost(evt);
            }
        });
        tfPalete.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfPaleteKeyPressed(evt);
            }
        });

        lbPalete.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbPalete.setText("Palete:");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Tranferência de Paletes da Rua");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbRuaOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(4, 4, 4)
                                .addComponent(tfRuaOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(lbPalete, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(4, 4, 4)
                                    .addComponent(tfPalete, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(lbConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lbRuaDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(4, 4, 4)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(tfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGap(10, 10, 10)
                                            .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(tfRuaDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnTransferir, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(122, 122, 122)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 544, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 772, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbRuaOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfRuaOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbPalete, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPalete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbRuaDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfRuaDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lbConfirmar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tfConfirmar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnTransferir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(73, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

}//GEN-LAST:event_jTable1MouseClicked

    private void btnTransferirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTransferirActionPerformed
        efetuarTransferencia();
}//GEN-LAST:event_btnTransferirActionPerformed

    private void btnTransferirKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnTransferirKeyPressed

}//GEN-LAST:event_btnTransferirKeyPressed

    private void tfConfirmarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            String confirm = tfConfirmar.getText();
            if (confirm.toUpperCase().equals("S")) {
                efetuarTransferencia();
            } else if (confirm.toUpperCase().equals("N")) {
                clearFields();
            } else {
                BoxPanel.showMessageDialog(null, "A confirmação é um campo obrigatório.");
                tfConfirmar.setText("");
                tfConfirmar.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfConfirmar.setText("");
            if(tfRuaDestino.isEditable()){
                tfRuaDestino.requestFocus();
            }else{
                tfRuaDestino.requestFocus();
            }
        }
}//GEN-LAST:event_tfConfirmarKeyPressed

    private void tfConfirmarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyReleased
        if (tfConfirmar.getText().length() > 0) {
            tfConfirmar.setText(tfConfirmar.getText().substring(0, 1));
        }
}//GEN-LAST:event_tfConfirmarKeyReleased

    private void tfRuaDestinoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfRuaDestinoFocusLost
        obterRua(tfRuaDestino,false);

}//GEN-LAST:event_tfRuaDestinoFocusLost

    private void tfRuaDestinoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRuaDestinoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            if(tfRuaDestino.getText().length() > 0){
                tfConfirmar.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfRuaDestino.setText("");
            tfPalete.requestFocus();
        }
}//GEN-LAST:event_tfRuaDestinoKeyPressed

    private void tfRuaOrigemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfRuaOrigemFocusLost
        obterRua(tfRuaOrigem,true);
}//GEN-LAST:event_tfRuaOrigemFocusLost

    private void tfRuaOrigemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRuaOrigemKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            if(tfRuaOrigem.getText().length() > 0){
                tfPalete.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfRuaOrigem.setText("");
        }
}//GEN-LAST:event_tfRuaOrigemKeyPressed

    private void tfPaleteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfPaleteFocusLost

}//GEN-LAST:event_tfPaleteFocusLost

    private void tfPaleteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfPaleteKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            if (tfPalete.getText().length() > 0) {
                tfRuaDestino.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfPalete.setText("");
            tfRuaOrigem.requestFocus();
        }
}//GEN-LAST:event_tfPaleteKeyPressed

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        clearFields();
    }//GEN-LAST:event_formAncestorAdded


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.enderecamento.gui.custom.WMSJButton btnTransferir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private modules.enderecamento.gui.custom.WMSJTable jTable1;
    private modules.enderecamento.gui.custom.WMSLabel lbConfirmar;
    private modules.enderecamento.gui.custom.WMSLabel lbPalete;
    private modules.enderecamento.gui.custom.WMSLabel lbRuaDestino;
    private modules.enderecamento.gui.custom.WMSLabel lbRuaOrigem;
    private modules.enderecamento.gui.custom.WMSJTextField tfConfirmar;
    private modules.enderecamento.gui.custom.WMSJTextField tfPalete;
    private modules.enderecamento.gui.custom.WMSJTextField tfRuaDestino;
    private modules.enderecamento.gui.custom.WMSJTextField tfRuaOrigem;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel6;
    // End of variables declaration//GEN-END:variables

    private void clearFields() {
        tfRuaOrigem.setText("");
        tfPalete.setText("");
        tfRuaDestino.setText("");
        tfConfirmar.setText("");
        tfRuaOrigem.requestFocus();
    }

    private void efetuarTransferencia() {
        Rua ruaOrigem = null;
        Rua ruaDestino = null;
        Palete palete = null;

        if(tfRuaOrigem.getText().length() == 0){
            Validation.getInstance().addErros("ruaOrigem", "Rua de origem é um campo obrigatório.");
        }
        if(tfPalete.getText().length() == 0){
            Validation.getInstance().addErros("palete", "Palete é um campo obrigatório.");
        }
        if(tfRuaDestino.getText().length() == 0){
            Validation.getInstance().addErros("ruaDestino", "Rua de destino é um campo obrigatório.");
        }
        if(tfRuaOrigem.getText().equals(tfRuaDestino.getText()) && tfRuaOrigem.getText().length() > 0){
            Validation.getInstance().addErros("ruaIgual", "A Rua de destino não pode ser o igual a de origem.");
        }
        if(Validation.getInstance().hasErrors()){
            BoxPanel.showMessageError(Funcoes.getListErros(Validation.getInstance().getErros()));
            return;
        }
        ruaOrigem = wmsFacade.obterRuaByName(tfRuaOrigem.getText());
        palete = wmsFacade.obterPaleteById(Integer.parseInt(tfPalete.getText()));
        ruaDestino = wmsFacade.obterRuaByName(tfRuaDestino.getText());

        if(ruaOrigem == null){
            BoxPanel.showMessageDialog(null, "Rua de origem não encontrada.");
            return;
        }
        if(ruaDestino == null){
            BoxPanel.showMessageDialog(null, "Rua de destino não encontrada.");
            return;
        }
        if(palete == null){
            BoxPanel.showMessageDialog(null, "Palete não encontrado.");
            return;
        }else{
            if(palete.getRua().getId() != ruaOrigem.getId()){
                BoxPanel.showMessageDialog(null, "Palete não encontrado na Rua informada.");
                return;
            }
        }

        if(palete!= null && ruaOrigem != null && ruaDestino != null){
            try {
                if (wmsFacade.moverPaleteRua(ruaOrigem, ruaDestino, palete)) {
                    BoxPanel.showMessageDialog(null, "Operaçao realizada com sucesso.");
                    clearFields();
                    DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
                    modelo.setNumRows(0);
                }
            } catch (EspacoExcedidoRuaException ex) {
                BoxPanel.showMessageDialog(null, ex.getMessage());
            }
        }
    }

    private void listarOcupacaoPaletes(List<OcupacaoPalete> ocupacaoPaletes) {
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);
        if(ocupacaoPaletes == null || ocupacaoPaletes.isEmpty()){
            BoxPanel.showMessageDialog(null, "A Rua informada não contém Palete.");
            return;
        }
        
        for (int i = 0; i < ocupacaoPaletes.size(); i++) {
            Integer paleteId = ocupacaoPaletes.get(i).getPalete().getId();
            Double ocupacao = ocupacaoPaletes.get(i).getOcupado();
            Double disponivel = ocupacaoPaletes.get(i).getDisponivel();
            DecimalFormat df = new DecimalFormat("##,###00.000");
            modelo.addRow(new Object[]{
                        paleteId, df.format(ocupacao), df.format(disponivel)
                    });
        }
    }

    private void obterRua(WMSJTextField textField, Boolean listar) {
        if(textField.getText().length() > 0){
            Rua rua = wmsFacade.obterRuaByName(textField.getText());
            if(rua != null){
                if(listar){
                    System.out.println(rua.getPaletes().size());
                    if(rua.getPaletes().isEmpty()){
                        BoxPanel.showMessageDialog(null, "A Rua informada não contém Palete");
                        tfRuaOrigem.setText("");
                        tfRuaOrigem.requestFocus();
                    }else{
                        listarOcupacaoPaletes(
                                wmsFacade.getListOcupacaoPaletes(rua,null, null, null)
                        );
                    }
                }
            }else{
                BoxPanel.showMessageDialog(null, "Rua não encontrada.");
                textField.setText("");
                textField.requestFocus();
            }
        }
    }

}
